package com.dwxt.parabolic.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.parabolic.dao.MenuMapper;
import com.dwxt.parabolic.dao.RoleMenuMapper;
import com.dwxt.parabolic.dao.UserRoleMapper;
import com.dwxt.parabolic.entity.*;
import com.dwxt.parabolic.entity.vo.MenuVo;
import com.dwxt.parabolic.utils.RequestUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    public BaseResult getMenuList() {

        //List<String> roleIdList = selectRoleIdListByUserId(userId);
        String userId = RequestUtil.getCurrentUserId();
        User user = userService.selectByPrimaryKey(userId);
        List<Menu> menuList = selectMenuIdListByRoleIds(Arrays.asList(user.getRoleId()));
        //处理列表，按层级返回菜单
        List<MenuVo> menuVoList = sortMenu(menuList);
        return BaseResult.ok(menuVoList);
    }

    private List<MenuVo> sortMenu(List<Menu> menuList) {
        List<MenuVo> topMenuList = menuList.stream().filter(menu -> menu.getLevel() == 1)
                .map(menu -> JsonUtils.jsonToPojo(JsonUtils.objectToJson(menu), MenuVo.class)).collect(Collectors.toList());

        List<MenuVo> menuVoList = topMenuList.stream().map(menuVo -> {
            List<MenuVo> collect = menuList.stream().filter(menu -> menu.getParentId().equalsIgnoreCase(menuVo.getId()))
                    .map(menu -> JsonUtils.jsonToPojo(JsonUtils.objectToJson(menu), MenuVo.class)).collect(Collectors.toList());
            menuVo.setChildMenus(collect);
            return menuVo;
        }).collect(Collectors.toList());

        return menuVoList;
    }

    /**
     * 查询角色所有菜单
     *
     * @param roleIdList
     * @return
     */
    public List<Menu> selectMenuIdListByRoleIds(List<String> roleIdList) {
        RoleMenuExample example = new RoleMenuExample();
        example.createCriteria().andRoleIdIn(roleIdList);
        List<String> menuIdList = roleMenuMapper.selectByExample(example).stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        MenuExample menuExample = new MenuExample();
        menuExample.setOrderByClause("level,create_time");
        menuExample.createCriteria().andIdIn(menuIdList);
        return menuMapper.selectByExample(menuExample);
    }


}
